package com.bjpowernode.other.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * 计算任务
 */
public class CountTask extends RecursiveTask<Long> {

    //任务分解的阈值
    private int threshold = 25;

    //区间
    private long begin;
    private long end;

    public CountTask(long begin, long end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum = 0;

        //判断任务是拆解还是计算
        if (end - begin < threshold) {
            //计算
            for (long i = begin; i <= end; i++) {
                sum += i;
            }
        }else{
            //任务拆解
            //找中间值
            long middle = (begin + end) / 2;

            //分解任务
            CountTask leftTask = new CountTask(begin, middle);
            CountTask rightTask = new CountTask(middle + 1, end);

            //执行任务  递归
            invokeAll(leftTask, rightTask);

            //只有当上面递归执行到if里面去计算出求和结果的时候，这里才会执行
            Long leftResult = leftTask.join();
            Long rightResult = rightTask.join();
            //合并结果
            sum = leftResult + rightResult;
        }

        return sum;
    }
}
